﻿using System;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Service;
using Icms.Core.Utils;
using Omu.ValueInjecter;

namespace Icms.WebUI.Builder
{
    public interface IParticipantMapper<T,T1> : IMapper<T,T1> where T1 : new() where T : class, new()
    {}
    public class ParticipantMapper<T> : IParticipantMapper<Participant, T> where T : new()
    {
        private readonly ICrudService<Participant> s;

        public ParticipantMapper(ICrudService<Participant> s)
        {
            this.s = s;
        }

        public T MapToInput(Participant e)
        {
            var input = new T();
            input.InjectFrom(e)
                .InjectFrom<NormalToNullables>(e);

            return input;
        }

        public Participant MapToEntity(T o, Guid? id)
        {
            var e = id.HasValue ? s.Get(id.Value) : new Participant();
            if (e == null)
                throw new IcmsException("this entity doesn't exist anymore");

            e.InjectFrom(o)
                .InjectFrom<NullGuidToEntity>(o)
                .InjectFrom<NullablesToNormal>(o);
            return e;
        }

        public T RemapInput(T createInput, Guid? id)
        {
            return MapToInput(MapToEntity(createInput, id));
        }
    }
}